package com.xianggu.agency.jdkProxy;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author chengjy
 * @date 2025/3/18
 */
public class Compiler {

    static String outputPath;

    static {

        String path = Compiler.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        File file = new File(path);
        try {
            outputPath = file.getCanonicalPath();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(outputPath);
    }
    public static void complie(File javaFile) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        // 获取文件管理器
        try(StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
            // 获取需要编译的文件对象
            Iterable<? extends JavaFileObject> compilationUnits =
                    fileManager.getJavaFileObjectsFromFiles(Arrays.asList(javaFile));
            // 编译参数，这里为空
            List<String> options = Arrays.asList("-d" , outputPath);

            // 创建编译任务
            JavaCompiler.CompilationTask task = compiler
                    .getTask(null, fileManager, null, options, null, compilationUnits);

            // 执行编译任务
            Boolean success = task.call();

            if (success) {
                System.out.println("编译成功");
            }else {
                System.out.println("编译失败");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
